package cn.edu.usst.cs.goldfish.booking.meetingroom.aop;

import cn.edu.usst.cs.goldfish.booking.meetingroom.handler.GoldfishBookingException;
import cn.edu.usst.cs.goldfish.booking.meetingroom.model.SysUser;
import cn.edu.usst.cs.goldfish.booking.meetingroom.service.UserService;
import cn.edu.usst.cs.goldfish.booking.meetingroom.web.dto.auth.RegisterRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class UserValidationAspect {

    private final UserService userService;

    public UserValidationAspect(UserService userService) {
        this.userService = userService;
    }
    @Before("execution(* cn.edu.usst.cs.goldfish.booking.meetingroom.web.controller.*.*(..))")
    public void logBeforeServiceMethods(@NonNull JoinPoint jp) {
        System.out.println("🛡 Calling: " + jp.getSignature());
    }
    @Before(value = "execution(* cn.edu.usst.cs.goldfish.booking.meetingroom.web.controller.AuthController.registerUser(..)) && args(registerRequest,session)", argNames = "registerRequest,session")
    public void validateUserRegistration(@NonNull RegisterRequest registerRequest, HttpSession session) {
        String email = registerRequest.getEmail();
        String nickname = registerRequest.getUsername();
        log.info("Validating user registration for email: {}, nickname: {}", email, nickname);
        userService.ensureNicknameNotTaken(nickname);
        userService.ensureEmailNotTaken(email);
    }

    @Before(value = "execution(* cn.edu.usst.cs.goldfish.booking.meetingroom.web.controller.AuthController.login(..)) && args(identifier,session)", argNames = "identifier,session")
    public void validateUserLogin(String identifier, HttpSession session) {
        log.info("Validating user login: {}", identifier);
        SysUser user = userService.findByCredential(identifier);
        if (user == null) {
            throw new GoldfishBookingException("用户不存在");
        }
    }
}